const mysql=require('../mysql/index')
const {success,error}=require('../model/index');
const query = require('../mysql/index');


//数据
class ListController{
    getList=async (ctx)=>{
        const {id,keyword,sortBy,sortType,pageSize,pageIndex}=ctx.query;
        let sql=`select * from users where 1=1 ` 
        let sqlCount=`select count(id) as total from users where 1=1 `
        if(id){
            sql+=`and id=${id} `
            sqlCount+=`and id=${id} `
        }
        if(keyword){
            sql+=`and title like "%${keyword}%" `
            sqlCount+=`and title like "%${keyword}%" `
        }
        if(sortBy && sortType){
            sql+=`order by ${sortBy} ${sortType} `
        }
        if(pageIndex && pageSize){
            sql+=`limit ${(pageIndex-1)*pageSize},${pageSize} `
            sqlCount+=`limit ${(pageIndex-1)*pageSize},${pageSize} `
        }
        const data=await query(sql)
        const count=await query(sqlCount)

        ctx.body=success({
            data:data,
            total:count[0].total
        })
    }
    //添加
    addList=async (ctx)=>{
        const {title,word,name}=ctx.request.body;
        const sql=`insert into users (title,word,name) values ("${title}","${word}","${name}" )`
        const data=await query(sql)
        console.log(data)
        if(data.affectedRows==1){
            ctx.body=success({
                code:1,
                message:'添加成功'
            })
        }else{
            ctx.body=error({
                code:-1,
                message:'添加失败'
            })
        }

    }
    //修改
    editList=async (ctx)=>{
        const {title,word,name,id}=ctx.request.body;
        const sql=`update users set title="${title}",word="${word}",name="${name}" where id=${id}`
        const data=await query(sql)
        console.log(data)
        if(data.affectedRows==1){
            ctx.body=success({
                code:1,
                message:'编辑成功'
            })
        }else{
            ctx.body=error({
                code:-1,
                message:'编辑失败'
            })
        }

    }
    //删除
    delList=async (ctx)=>{
        const {id}=ctx.params;
        const sql=`delete from users where id=${id} `
        const data=await query(sql)
        console.log(data)
        if(data.affectedRows==1){
            ctx.body=success({
                code:1,
                message:'删除 成功'
            })
        }else{
            ctx.body=error({
                code:-1,
                message:'删除 失败'
            })
        }
    }
}


module.exports=new ListController()